<template>
  <div class="X_Plot_content">
    <div class="X_Plot_leftbox">
      <!-- left -->
      <div class="X_Plot_left">
        <div class="X_Plot_left_item" v-for="(item, index) in imgdata" :key="index" @mouseenter="hoverIndex = index"
          @mouseleave="hoverIndex = -1">
          <div style="position: relative">
            <TextTooltip class="box-item" :tooltipText="item.title">
              <template #txto>
                <el-popover placement="right" trigger="click" :visible="item.visible">
                  <div v-if="item.src.imgurl === 'dw'">
                    <div v-for="(poitem) in [
                      {
                        url: {
                          imgname: 'leftic',
                          imgurl: 'dian'
                        },
                        btn: {
                          imgname: 'leftic',
                          imgurl: 'dianbtn'
                        },
                        tit: '点',
                        num: 1,
                      },
                      {
                        url: {
                          imgname: 'leftic',
                          imgurl: 'xian'
                        },
                        btn: {
                          imgname: 'leftic',
                          imgurl: 'xianbtn'
                        },
                        tit: '线',
                        num: 2,
                      },
                      // {
                      //   url: 'leftic/ju',
                      //   btn: 'leftic/jubtn',
                      //   tit: '矩形',
                      //   num: 3,
                      // },
                      {
                        url: {
                          imgname: 'leftic',
                          imgurl: 'yuan'
                        },
                        btn: {
                          imgname: 'leftic',
                          imgurl: 'yuanbtn'
                        },
                        tit: '圆',
                        num: 4,
                      },
                      {
                        url: {
                          imgname: 'leftic',
                          imgurl: 'duo'
                        },
                        btn: {
                          imgname: 'leftic',
                          imgurl: 'duobtn'
                        },
                        tit: '多边形',
                        num: 5,
                      },
                      {
                        url: {
                          imgname: 'leftic',
                          imgurl: 'tuoyuan'
                        },
                        btn: {
                          imgname: 'leftic',
                          imgurl: 'tuoyuanbtn'
                        },
                        tit: '椭圆',
                        num: 13,
                      },
                      {
                        url: {
                          imgname: 'leftic',
                          imgurl: 'shan'
                        },
                        btn: {
                          imgname: 'leftic',
                          imgurl: 'shanbtn'
                        },
                        tit: '扇形',
                        num: 14,
                      },
                      {
                        url: {
                          imgname: 'leftic',
                          imgurl: 'shanhuan'
                        },
                        btn: {
                          imgname: 'leftic',
                          imgurl: 'shanhuanbtn'
                        },
                        tit: '扇环',
                        num: 15,
                      },
                      // {
                      //   url: 'leftic/shan',
                      //   btn: 'leftic/shanbtn',
                      //   tit: '测向线',
                      //   num: 16,
                      // },
                      {
                        url: {
                          imgname: 'leftic',
                          imgurl: 'shan'
                        },
                        btn: {
                          imgname: 'leftic',
                          imgurl: 'shanbtn'
                        },
                        tit: '航迹线',
                        num: 17,
                      },
                      {
                        url: {
                          imgname: 'leftic',
                          imgurl: 'shan'
                        },
                        btn: {
                          imgname: 'leftic',
                          imgurl: 'shanbtn'
                        },
                        tit: '目标标绘',
                        num: 18,
                      },
                    ]" :key="poitem">
                      <div style="display: flex; padding: 5px 0; cursor: pointer"
                        @click="actpopoImage(poitem, poitem.num, item)">
                        <img style="margin-right: 8px" width="16px" height="16px"
                          :src="clipopover(poitem, poitem.num)" />
                        <div :style="{
                          color: popoindex === poitem.num ? '#3471FE' : '',
                        }">
                          {{ poitem.tit }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-else-if="item.src.imgurl === 'cz'">
                    <div v-for="(poitem) in [
                      {
                        url: 'leftic/zx',
                        btn: 'leftic/zxbtn',
                        tit: '空间测距',
                        num: 6,
                      },
                      {
                        url: 'leftic/sj',
                        btn: 'leftic/sjbtn',
                        tit: '三角测距',
                        num: 7,
                      },
                      {
                        url: 'leftic/mj',
                        btn: 'leftic/mjbtn',
                        tit: '面积测量',
                        num: 8,
                      },
                      {
                        url: 'leftic/pd',
                        btn: 'leftic/pdbtn',
                        tit: '坡度测量',
                        num: 9,
                      },
                      {
                        url: 'leftic/ts',
                        btn: 'leftic/tsbtn',
                        tit: '通视范围',
                        num: 10,
                      },
                    ]" :key="poitem">
                      <div style="display: flex; padding: 5px 0; cursor: pointer"
                        @click="actpopoImage(poitem, poitem.num, item)">
                        <img style="margin-right: 8px" width="16px" height="16px"
                          :src="clipopover(poitem, poitem.num)" />
                        <div :style="{
                          color: popoindex === poitem.num ? '#3471FE' : '',
                        }">
                          {{ poitem.tit }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-else-if="item.src.imgurl === 'diwd'">
                    <div v-for="(poitem) in [
                      {
                        url: 'leftic/qyjt',
                        btn: 'leftic/qyjtbtn',
                        tit: '区域截图',
                        num: 11,
                      },
                      {
                        url: 'leftic/qpjt',
                        btn: 'leftic/qpjtbtn',
                        tit: '全屏截图',
                        num: 12,
                      },
                    ]" :key="poitem">
                      <div style="display: flex; padding: 5px 0; cursor: pointer"
                        @click="actpopoImage(poitem, poitem.num, item)">
                        <img style="margin-right: 8px" width="16px" height="16px"
                          :src="clipopover(poitem, poitem.num)" />
                        <div :style="{
                          color: popoindex === poitem.num ? '#3471FE' : '',
                        }">
                          {{ poitem.tit }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <template #reference>
                    <img :class="isdelbool ? 'shake' : ''" style="cursor: pointer" @click="activateImage(item, index)"
                      :src="getImageSource(item, index)" />
                  </template>
                </el-popover>
              </template>
            </TextTooltip>
            <!--  -->
            <div v-if="item.src.imgurl !== 'sez' && isdelbool" class="X_Plot_left_item_active">
              <img v-show="item.isdel" src="@/assets/img/27/qpdialog.png" @click="addimg(item)" />
              <img v-show="!item.isdel" src="@/assets/img/27/gbdialog.png" @click="delimg(item)" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--  -->
    <draw-point v-if="showDrawDialog" :showDrawDialog="showDrawDialog" dioid="drawPointDialog" :pointfrom="pointfrom"
      :isapi="isponit" @pointfromcol="changepointfrom" />
    <!--  -->
    <draw-polyline v-if="showDrawPolylineDialog" :showDrawDialog="showDrawPolylineDialog" dioid="drawPolylineDialog"
      :polylinefrom="polylinefrom" :isapi="isponit" @polylinefromcol="changepolylinefrom" />
    <!--  -->
    <drawPolygon v-if="showDrawpolygonDialog" :showDrawDialog="showDrawpolygonDialog" dioid="drawpolygonDialog"
      :polygonfrom="polygonfrom" :isapi="isponit" @polygonfromcol="changepolygonfromcol" />
    <!--  -->
    <drawCircle v-if="showDrawcircularDialog" :showDrawDialog="showDrawcircularDialog" dioid="drawcircularDialog"
      :circularfrom="circularfrom" :isapi="isponit" @circularfromcol="changecircularfromcol" />


    <drawEllipse v-if="showDrawEllipseDialog" :showDrawDialog="showDrawEllipseDialog" dioid="drawcirEllipseDialog"
      :circularfrom="ellipsefrom" :isapi="isponit" @circularfromcol="changeellipsefromcol" />

    <drawSector v-if="showDrawSectorDialog" :showDrawDialog="showDrawSectorDialog" dioid="drawSectorDialog"
      :circularfrom="sectorfrom" :isapi="isponit" @circularfromcol="changesectorfromcol" />


    <drawSectorRing v-if="showDrawSectorRingDialog" :showDrawDialog="showDrawSectorRingDialog"
      dioid="drawSectorRingDialog" :circularfrom="sectorRingfrom" :isapi="isponit"
      @circularfromcol="changesectorringfromcol" />
    <!--  -->

    <drawLabel v-if="showDrawLableDialog" :showDrawDialog="showDrawLableDialog" dioid="drawLableDialog"
      :labelfrom="labelfrom" :isapi="isponit" @labelfromcol="changelabelfromcol" />
    <!--  -->
  </div>

  <Diopositi v-model:dialogvis="showdiopositi" dioid="diopositid" />

  <TrackTable :showTrackTableDialog="showTrackTable" dioid="trackTableDialog" :data="TrackTableData" />
  <!-- @Direfindfromcol="changeDirefindfrom" -->
  <el-dialog title="设置扇环参数" v-model="dialogVisible" @close="closeDialog">
    <template #content>
      <el-form :model="form" label-width="100px">
        <el-form-item label="内半径 (米)">
          <el-input v-model="form.innerRadius" type="number"></el-input>
        </el-form-item>
        <el-form-item label="外半径 (米)">
          <el-input v-model="form.outerRadius" type="number"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmParams">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  ref,
  onMounted,
  onBeforeUnmount,
  nextTick,
  getCurrentInstance,
  watch
} from "vue";
import {
  getPoint,
  getDrawLine2,
  getDrawLine1,
  getTrackLine,
  getTrackLine2,
  getLayer,
  getPolygon,
  getCircle,
  getEllipse,
  getSector,
  getSectorRing,

} from "@/api";
import {
  getAssetsFile,
  JIcon,
  Point3D,
  iscolor,
  extractAlphaFromRgba,
  LineStyle,
  Area,
  FontStyle
} from "@/utils/compnt.js";
import Sortable from "sortablejs";
import {
  DrawPoint,
  DrawPolygon,
  DrawRectangle,
  DrawSector,
  DrawCircle,
  MeasureLineSpace,
  MeasureAreaSpace,
  SlopeAspectAnalysis,
  MotionTrajectory,
  VisibilityAnalyzer,
  SectorRingDrawer,

} from "@/utils/libcesium/index";
import { DrawTool } from "@/utils/cesiumExp-plot/src/index.js";
import {
  MeasureTool,
  MeasureAzimutht,
} from "@/utils/CesiumExp-measure/src/index.js";
//
import drawPoint from "@/components/27/pop/drawPoint.vue"; // 根据实际路径调整
import Diopositi from "@/components/27/pop/diopositi.vue";
import TextTooltip from "./components/TextTooltip.vue";
import drawPolygon from "@/components/27/pop/drawPolygon.vue";
import drawPolyline from "@/components/27/pop/drawPolyline.vue";
import drawLabel from "@/components/27/pop/drawLabel.vue"
import drawCircle from '@/components/27/pop/drawCircle.vue'
import drawEllipse from '@/components/27/pop/drawEllipse.vue'
import drawSector from '@/components/27/pop/drawSector.vue'
import drawSectorRing from '@/components/27/pop/drawSectorRing.vue'
import TrackTable from "@/components/27/pop/TrackTable.vue";
import boatModel from "@/assets/glb/boat.glb";

//
import { useWebSocketStore } from '@/stores/websocket';
const websocketStore = useWebSocketStore();
// 响应式数据
const { proxy } = getCurrentInstance();


const imgdata = ref([
  {
    id: 0,
    title: "拖动",
    src: {
      imgname: '27',
      imgurl: 'sz'
    },
    hover: {
      imgname: 'hover',
      imgurl: 'szhover'
    },
    btn: {
      imgname: 'btn',
      imgurl: 'szbtn'
    },
    isdel: false,
    visible: false,
    shouldToggleBack: false,
  },
  {
    id: 1,
    title: "标记",
    src: {
      imgname: '27',
      imgurl: 'dw'
    },
    hover: {
      imgname: 'hover',
      imgurl: 'dwhover'
    },
    btn: {
      imgname: 'btn',
      imgurl: 'dwbtn'
    },
    isdel: false,
    visible: false,
    shouldToggleBack: false,
  },
  {
    id: 2,
    title: "放大",
    src: {
      imgname: '27',
      imgurl: 'fd'
    },
    hover: {
      imgname: 'hover',
      imgurl: 'fdhover'
    },
    btn: {
      imgname: 'btn',
      imgurl: 'fdbtn'
    },
    isdel: false,
    visible: false,
    shouldToggleBack: true,
    scale: 2,
  },
  {
    id: 3,
    title: "缩小",
    src: {
      imgname: '27',
      imgurl: 'sx'
    },
    hover: {
      imgname: 'hover',
      imgurl: 'sxhover'
    },
    btn: {
      imgname: 'btn',
      imgurl: 'sxbtn'
    },
    isdel: false,
    visible: false,
    shouldToggleBack: true,
    scale: -2,
  },
  {
    id: 4,
    title: "测距",
    src: {
      imgname: '27',
      imgurl: "cz",
    },
    hover: {
      imgname: 'hover',
      imgurl: "czhover",
    },
    btn: {
      imgname: 'btn',
      imgurl: "czbtn",
    },
    isdel: false,
    visible: false,
    shouldToggleBack: false,
  },
  {
    id: 5,
    title: "定位",
    src: {
      imgname: '27',
      imgurl: "diw",
    },
    hover: {
      imgname: 'hover',
      imgurl: "diwhover",
    },
    btn: {
      imgname: 'btn',
      imgurl: "diwbtn",
    },
    isdel: false,
    visible: false,
    shouldToggleBack: true,
  },
  {
    id: 6,
    title: "设置",
    src: {
      imgname: '27',
      imgurl: "sez",
    },
    hover: {
      imgname: 'hover',
      imgurl: "sezhover",
    },
    btn: {
      imgname: 'btn',
      imgurl: "sezbtn",
    },
    // isdel: false,
    visible: false,
    shouldToggleBack: false,
  },
  {
    id: 7,
    title: "截图",
    src: {
      imgname: '27',
      imgurl: "jt",
    },
    hover: {
      imgname: 'hover',
      imgurl: "jthover",
    },
    btn: {
      imgname: 'btn',
      imgurl: 'jtbtn'
    },
    isdel: false,
    visible: false,
    shouldToggleBack: false,
  },
  {
    id: 8,
    title: "字符",
    src: {
      imgname: '27',
      imgurl: "zi",
    },
    hover: {
      imgname: 'hover',
      imgurl: "zihover",
    },
    btn: {
      imgname: 'btn',
      imgurl: "zibtn",
    },
    isdel: false,
    visible: false,
    shouldToggleBack: false,
  },
]);

const pointfrom = ref({
  LayerName: "默认图层",
  KeyValue: "",
  LayerID: 1,
  Icon: {},
  Heading: 0,
  StartP: {},
  DesValue: "",
});

const polylinefrom = ref({
  LayerName: "默认图层",
  LayerID: 1,
  KeyValue: "",
  LineStyle: {},
  Point: [],
  DesValue: "",
});

const polygonfrom = ref({
  LayerName: "默认图层",
  KeyValue: "",
  LayerID: 1,
  Style: {},
  Point: [],
  DesValue: "",
})

const circularfrom = ref({
  LayerName: "默认图层",
  KeyValue: "",
  LayerID: 1,
  Style: {},
  CenterP: {},
  Radius: '',
  DesValue: "",
})
const ellipsefrom = ref({
  LayerName: "默认图层",
  KeyValue: "",
  LayerID: 1,
  Style: {},
  CenterP: {},
  Heading: {},
  DesValue: "",
})
const sectorfrom = ref({
  LayerName: "默认图层",
  KeyValue: "",
  LayerID: 1,
  Style: {},
  CenterP: {},
  Heading: 0,
  DesValue: "",
})
const sectorRingfrom = ref({
  LayerName: "默认图层",
  KeyValue: "",
  LayerID: 1,
  Style: {},
  CenterP: {},
  Heading: 0,
  InnerRadius: 0,
  OuterRadius: 0,
  StartAngle: 0,
  EndAngle: 0,
  DesValue: "",
})

const labelfrom = ref({
  LayerName: "默认图层",
  KeyValue: '',
  LayerID: 1,
  Title: '',
  FontStyle: {},
  StartP: {},
  StartX: '',
  StartY: '',
})


const isdelbool = ref(false);
const hoverIndex = ref(-1);
const activeIndex = ref(-1);
const sortable = ref(null);
const popoindex = ref(0);
const labelTool = ref(null);
const isponit = ref(false);
//


// 方法
const activateImage = (item, index) => {
  clearTrajectory();
  console.log('activeIndex.value', item, index, activeIndex.value);

  if (activeIndex.value !== -1) {
    activeIndex.value = -1;
    imgdata.value.forEach((ee) => {
      ee.visible = false;
    });
  }

  if (item.shouldToggleBack) {
    activeIndex.value = index;
  } else {
    activeIndex.value = activeIndex.value === index ? -1 : index;
  }

  if (item.src.imgurl == "sez" && !isdelbool.value) {
    isdelbool.value = true;
  } else {
    isdelbool.value = false;
  }

  if (item.src.imgurl != "sz" || item.src.imgurl != "sez") {
    switch (item.src.imgurl) {
      case "dw":
        item.visible = !item.visible;
        imgdata.value[4].visible = false;
        imgdata.value[7].visible = false;
        imgdata.value[8].visible = false;
        break;
      case "cz":
        item.visible = !item.visible;
        imgdata.value[1].visible = false;
        imgdata.value[7].visible = false;
        imgdata.value[8].visible = false;
        break;
      case "diwd":
        item.visible = !item.visible;
        imgdata.value[1].visible = false;
        imgdata.value[4].visible = false;
        imgdata.value[8].visible = false;
        break;
      case "zi":
        if (pointTools.value) {
          let pointTool = new DrawTool(viewer);
          pointTool.removeOne(pointTools.value);
        }
        let labelData = {
          name: "文字",
          type: "label",
          iconImg: "./easy3d/images/plot/label.png",
          style: {
            text: "文字标题",
            fillColor: "#fff",
            heightReference: 0,
            showBackground: true,
            backgroundColor: "#000",
            scale: 1,
          },
          styleType: "label",
        };
        let labelTool = new DrawTool(window.viewer, {
          canEdit: true,
        });
        pointTools.value = labelTool;
        if (!labelTool) return;
        labelTool.start(labelData);

        editstatus(labelTool, "文字", "开始");



        break;
      case "fd":
        if (!window.viewer) return;
        const scaleFactor = item.scale;
        const fdcameraPosition = window.viewer.camera.position;
        const fdcameraHeight = window.viewer.camera.positionCartographic.height;
        const fdnewHeight = Math.max(50, fdcameraHeight / scaleFactor);
        const fdcartographic =
          Cesium.Cartographic.fromCartesian(fdcameraPosition);
        fdcartographic.height = fdnewHeight;
        const fdnewPosition =
          Cesium.Ellipsoid.WGS84.cartographicToCartesian(fdcartographic);
        window.viewer.camera.setView({
          destination: fdnewPosition,
          orientation: {
            heading: window.viewer.camera.heading,
            pitch: window.viewer.camera.pitch,
            roll: window.viewer.camera.roll,
          },
        });
        break;
      case "sx":
        if (!window.viewer) return;
        const scaleFactorSx = Math.abs(item.scale);
        const cameraPosition = window.viewer.camera.position;
        const cameraHeight = window.viewer.camera.positionCartographic.height;
        const newHeight = cameraHeight * scaleFactorSx;
        const cartographic = Cesium.Cartographic.fromCartesian(cameraPosition);
        cartographic.height = newHeight;
        const newPosition =
          Cesium.Ellipsoid.WGS84.cartographicToCartesian(cartographic);
        window.viewer.camera.setView({
          destination: newPosition,
          orientation: {
            heading: window.viewer.camera.heading,
            pitch: window.viewer.camera.pitch,
            roll: window.viewer.camera.roll,
          },
        });
        break;
      case "diw":
        showdiopositi.value = true;
        break;
    }
  } else {
    imgdata.value[1].visible = false;
    imgdata.value[4].visible = false;
    imgdata.value[7].visible = false;
    imgdata.value[8].visible = false;
  }

  if (item.shouldToggleBack) {
    setTimeout(() => {
      activeIndex.value = -1;
    }, 300);
  }
};

const getImageSource = (item, index) => {
  if (index === activeIndex.value) {
    return getAssetsFile(item.btn.imgname, item.btn.imgurl || item.hover.imgname, item.hover.imgurl || item.src.imgname, item.src.imgurl);
  }
  return hoverIndex.value === index
    ? getAssetsFile(item.hover.imgname, item.hover.imgurl || item.src.imgname, item.src.imgurl)
    : getAssetsFile(item.src.imgname, item.src.imgurl);
};

const addimg = (item) => {
  console.log("添加");
  let foundIndex = -1;
  imgdata.value.forEach((add, index) => {
    if (!add.isdel) {
      return;
    } else if (add.src === item.src.imgurl && add.isdel === item.isdel) {
      add.isdel = false;
      foundIndex = index;
    }
  });

  if (foundIndex !== -1) {
    // 从原位置删除该项
    const [movedItem] = imgdata.value.splice(foundIndex, 1);
    // 添加到数组开头
    imgdata.value.unshift(movedItem);
  }
};

const delimg = (item) => {
  console.log("删除");
  let foundIndex = -1;
  imgdata.value.forEach((add, index) => {
    if (add.isdel) {
      return;
    } else if (add.src === item.src.imgurl && add.isdel === item.isdel) {
      add.isdel = true;
      foundIndex = index;
    }
  });

  if (foundIndex !== -1) {
    // 从原位置删除该项
    const [movedItem] = imgdata.value.splice(foundIndex, 1);
    // 添加到数组末尾
    imgdata.value.push(movedItem);
  }
};

const updateActiveIndex = (oldIndex, newIndex) => {
  if (activeIndex.value === oldIndex) {
    activeIndex.value = newIndex;
  } else if (oldIndex < newIndex) {
    if (activeIndex.value > oldIndex && activeIndex.value <= newIndex) {
      activeIndex.value--;
    }
  } else {
    if (activeIndex.value >= newIndex && activeIndex.value < oldIndex) {
      activeIndex.value++;
    }
  }
};

const onDragEnd = (evt) => {
  if (evt.oldIndex === undefined || evt.newIndex === undefined) return;
  if (evt.oldIndex === evt.newIndex) return;

  // 创建数组副本（避免污染原数组）
  const newArray = [...imgdata.value];

  // 执行元素移动
  const [movedItem] = newArray.splice(evt.oldIndex, 1);
  newArray.splice(evt.newIndex, 0, movedItem);

  // 强制更新
  const temp = newArray;
  imgdata.value = [];
  nextTick(() => {
    imgdata.value = temp;
    console.log(imgdata.value);
    updateActiveIndex(evt.oldIndex, evt.newIndex);
  });

  // 更新相关状态
};

const showDrawDialog = ref(false);
const showDrawPolylineDialog = ref(false);
const showDrawpolygonDialog = ref(false)
const showDrawcircularDialog = ref(false)
const showDrawEllipseDialog = ref(false)
const showDrawSectorDialog = ref(false)
const showDrawSectorRingDialog = ref(false)
const handler = ref(false);
const showDrawLableDialog = ref(false)


const pointTools = ref(null);
const editpointTools = ref(null);
const entityData = ref(null);
const trackTool = ref(null);
const visibilityAnalyzer = ref(null);
const clearTrajectory = () => {
  if (trackTool.value) {
    trackTool.value.clear();
    trackTool.value = null;
  }
  if (visibilityAnalyzer.value) {
    visibilityAnalyzer.value.clearAll();
    visibilityAnalyzer.value = null;
  }
};

const actpopoImage = (item, index, heaitem, tree) => {
  console.log(tree, pointfrom.value)
  if (tree === undefined) {
    pointfrom.value.LayerName = '默认图层'
  }
  if (activeIndex.value !== -1) {
    activeIndex.value = -1;
    imgdata.value.forEach((ee) => {
      ee.visible = false;
    });
  }
  if (item.tit === "目标标绘") {
    const event = new CustomEvent('mbbh', {
      detail: {
        name: '目标标绘',
      }
    });
    window.dispatchEvent(event);
  }

  popoindex.value = index;

  if (item.tit !== "区域截图" && !isRegionScreenshotActive.value) {
    if (cleanupScreenshotHandler.value) {
      cleanupScreenshotHandler.value(); // 直接调用清理函数
      cleanupScreenshotHandler.value = null;
    }
  }

  // 初始化绘制
  if (pointTools.value) {
    let pointTool = new DrawTool(viewer);
    pointTool.removeOne(pointTools.value);
  }

  if (window.viewer) {
    console.log("window.viewer", window.viewer);
    heaitem.visible = false;
    switch (item.tit) {
      case "点":
        let pointData = {
          name: "点",
          type: "point",
          // iconImg: "./easy3d/images/plot/point.png",
          styleType: "point",
        };
        let pointTool = new DrawTool(viewer, {
          canEdit: true,
        });
        pointTools.value = pointTool;
        if (!pointTool) return;
        pointTool.start(pointData);
        editstatus(pointTool, "点", "开始", tree);
        break;
      case "线":
        let polylineData = {
          name: "线",
          type: "polyline",
          // iconImg: "./easy3d/images/plot/polyline.png",
          styleType: "polyline",
          style: {
            clampToGround: true,
            color: "#ffff00",
          },
        };
        let polylineTool = new DrawTool(viewer, {
          canEdit: true,
        });
        pointTools.value = polylineTool;
        if (!polylineTool) return;
        polylineTool.start(polylineData);
        editstatus(polylineTool, "线", "开始", tree);

        break;
      // case "矩形":
      //   // let RectangleData = {
      //   //   name: "矩形",
      //   //   type: "rectangle",
      //   //   // iconImg: "./easy3d/images/plot/rectangle.png",
      //   //   styleType: "rectangle",
      //   //   style: {
      //   //     color: "#00FFFF",
      //   //     colorAlpha: 0.3,
      //   //     outline: true,
      //   //     outlineColor: "#ff0000",
      //   //     heightReference: 1000,
      //   //   },
      //   // };
      //   // let rectangleTool = new DrawTool(viewer, {
      //   //   canEdit: true,
      //   // });
      //   // pointTools.value = rectangleTool;
      //   // if (!rectangleTool) return;
      //   // rectangleTool.start(RectangleData);
      //   // editstatus(rectangleTool, "矩形", "开始", tree);
      //   break;
      case "圆":
        let circleData = {
          name: "圆",
          type: "circle",
          // iconImg: "./easy3d/images/plot/point.png",
          styleType: "circle",
          style: {
            clampToGround: true,
            color: "#ffff00",
            outline: false,
            outlineColor: "#ff0000",
            outlineWidth: 1,
            heightReference: 1,
          },
        };
        let circleTool = new DrawTool(viewer, {
          canEdit: true,
        });
        pointTools.value = circleTool;
        if (!circleTool) return;
        circleTool.start(circleData);
        editstatus(circleTool, "圆", "开始", tree);
        break;
      case "多边形":
        let polygonData = {
          name: "面",
          type: "polygon",
          styleType: "polygon",
          style: {
            color: "#00FFFF",
            colorAlpha: 0.3,
            outline: true,
            outlineColor: "#ff0000",
            heightReference: 1,
          },
        };
        let polygonTool = new DrawTool(viewer, {
          canEdit: true,
        });
        pointTools.value = polygonTool;
        if (!polygonTool) return;
        polygonTool.start(polygonData);
        editstatus(polygonTool, "多边形", "开始", tree);
        break;
      case "椭圆":
        // DrawEllipse;

        let ellipseData = {
          type: "ellipse",
          style: {
            color: "#ff0000",
            colorAlpha: 0.5,
            outline: true,
            outlineColor: "#000000",
            outlineWidth: 2,
            fill: true,
            // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            height: 0
          }
        };

        const ellipseDrawer = new DrawTool(window.viewer, {
          canEdit: true,
        });
        pointTools.value = ellipseDrawer;
        ellipseDrawer.start(ellipseData);
        editstatus(ellipseDrawer, "椭圆", "开始", tree);
        break;
      case "扇形":

        let sectorData = {
          type: "sector",
          style: {
            color: 'rgba(255, 0, 0, 1)',
            outline: true,
            outlineColor: 'black',
            outlineWidth: 2,
            heightReference: Cesium.HeightReference.NONE
          }
        };
        let sectorTool = new DrawTool(viewer, {
          canEdit: true,
        });
        if (!sectorTool) return;
        pointTools.value = sectorTool;
        // sectorTool.on("startEdit", (entityObj, entity) => {
        //   console.log("开始编辑", entityObj);
        // })

        sectorTool.start(sectorData);
        editstatus(sectorTool, "扇形", "开始", tree);



        break;
      case "扇环":
        let ringData = {
          type: "ring",
          style: {
            "innerRadius": 300,
            "outerRadius": 1500,
            "startAngle": 30,
            "endAngle": 120,
            "material": Cesium.Color.BLUE.withAlpha(0.3),
            "outline": true,
            "outlineColor": Cesium.Color.YELLOW,
            "outlineWidth": 2
          }
        };
        let ringTool = new DrawTool(viewer, {
          canEdit: true,
        });
        ringTool.start(ringData);
        editstatus(ringTool, "扇环", "开始", tree);


        break;
      case "航迹线":
        getTrackLineapi();
        // clearTrajectory();
        // const trajectoryData = [
        //   [116.4, 39.9, 50.0],
        //   [116.5, 39.95, 80.0],
        // ];

        // // console.log("1", boatModel);
        // motionTrajectoryInstance.value = new MotionTrajectory(
        //   window.viewer,
        //   trajectoryData,
        //   boatModel
        // );
        // motionTrajectoryInstance.value.initLocus();

        break;

      case "区域截图":
        if (!isRegionScreenshotActive.value) {
          console.log("区域截图功能当前被禁用，忽略本次截图请求");
          return;
        }
        initScreenshot(window.viewer);
        break;
      case "全屏截图":
        takeScreenshot(window.viewer);
        break;
      default:
        break;
      case "空间测距":
        let handlerLine = new MeasureLineSpace({
          viewer: window.viewer,
          Cesium: window.cesium,
          // callback: (data) => {
          // drawPointCallBack(data);
          // handler.value.destroy();
          // },
        });

        handlerLine.start();
        break;
      case "三角测距":
        break;
      case "面积测量":
        let handlerArea = new MeasureAreaSpace({
          viewer: window.viewer,
          Cesium: window.Cesium,
          // callback: (data) => {
          // drawPointCallBack(data);
          // handler.value.destroy();
          // },
        });
        handlerArea.start();
        break;
      case "坡度测量":
        let handlerSlopeAspectAnalysis = new SlopeAspectAnalysis(
          window.viewer,
          window.Cesium
        );
        handlerSlopeAspectAnalysis.enableRegionSelection();
        break;
      case "通视范围":
        console.log("通视范围", window.viewer);
        visibilityAnalyzer.value = new VisibilityAnalyzer(window.viewer);
        visibilityAnalyzer.value.start();
        break;
    }
  }
};

const callbacks = (data) => {
  console.log(data);
};
const clipopover = (item, index) => {
  if (index === popoindex.value) {
    console.log("popoindex.value", popoindex.value);
    return getAssetsFile(item.btn.imgname, item.btn.imgurl);
  } else {
    return getAssetsFile(item.url.imgname, item.url.imgurl);
  }
};
const sectorRingDrawer = ref(null);
const dialogVisible = ref(false);
const formRing = ref({
  innerRadius: 1000,
  outerRadius: 5000
});
const startSectorRingDrawing = () => {
  dialogVisible.value = true;
};

const closeDialog = () => {
  dialogVisible.value = false;
};
const confirmParams = () => {
  const params = {
    innerRadius: Number(form.value.innerRadius),
    outerRadius: Number(form.value.outerRadius)
  };
  sectorRingDrawer.value = new SectorRingDrawer(viewer.value, params);
  sectorRingDrawer.value.startDrawing();
  dialogVisible.value = false;
};
const btnType = ref(false);
// 生命周期
onMounted(() => {
  sortable.value = new Sortable(document.querySelector(".X_Plot_left"), {
    animation: 150,
    draggable: ".X_Plot_left_item",
    onUpdate: () => false,
    onSort: () => false,
    onMove: (evt) => {
      // 只有 isdelbool.value 为 true 时才允许拖动
      return isdelbool.value;
    },
    onEnd: onDragEnd,
  });
  //点
  window.addEventListener("draw-point-cancel", function (e) {

    showDrawDialog.value = false
    if (handler.value) {
      handler.value.clear();
      handler.value = false;
    }

    getPointapi();
    getLayerapi()
  });
  // 线
  window.addEventListener("draw-polyline-cancel", function (e) {

    showDrawPolylineDialog.value = false
    if (handler.value) {
      handler.value.clear();
      handler.value = false;
    }
    getDrawLine2api();
    getLayerapi()
  });
  // 面
  window.addEventListener("draw-polygon-cancel", function (e) {

    showDrawpolygonDialog.value = false
    if (handler.value) {
      handler.value.clear();
      handler.value = false;
    }
    getPolygonapi()
    getLayerapi()
  });
  // 圆弹窗请求关闭
  window.addEventListener("draw-circular-cancel", function (e) {
    showDrawcircularDialog.value = false
    if (handler.value) {
      handler.value.clear();
      handler.value = false;
    }
    getCircleapi()
    getLayerapi()
  });
  // 椭圆弹窗请求关闭
  window.addEventListener("draw-ellipse-cancel", function (e) {
    showDrawEllipseDialog.value = false
    if (handler.value) {
      handler.value.clear();
      handler.value = false;
    }
    getEllipseapi()
    getLayerapi()
  });
  //
  window.addEventListener("draw-sector-cancel", function (e) {

    showDrawSectorDialog.value = false
    if (handler.value) {
      handler.value.clear();
      handler.value = false;
    }
    getSectorapi()
    getLayerapi()
  });
  //
  window.addEventListener("draw-sectorring-cancel", function (e) {
    editpointTools.value.endEdit()
    showDrawSectorRingDialog.value = false
    if (handler.value) {
      handler.value.clear();
      handler.value = false;
    }
    getSectorRingapi()
    getLayerapi()
  });
  // getLayerapi()


  window.addEventListener("track-table-click", function (e) {
    clearTrajectory();
    trackTool.value = new MotionTrajectory(
      window.viewer,
      { features: [e.detail] },
      boatModel
    );
    trackTool.value.initLocus();
  });
  //
  window.addEventListener("track-table-cancel", function (e) {
    showTrackTable.value = false;
  });
  //

  nextTick(() => {
    proxy.$mitt.on("cesiumInitialized", async (e) => {
      await getLayerapi()
      await getPointapi();
      await getDrawLine2api();
      await getDrawLine1api();
      await getPolygonapi();
      await getCircleapi();
      await getEllipseapi();
      await getSectorapi();
      await getSectorRingapi();
    });

    proxy.$mitt.on('drawdata', (e) => {
      actpopoImage(e.rightd, e.rightd.num, imgdata.value[1], {
        treenode: e.treenode,
        treedata: e.treedata
      })
    })
  });

  watch(() => websocketStore.messages, (newMessages) => {
    if (websocketStore.lastMessage) {
      const jsondata = JSON.parse(websocketStore.lastMessage.data)
      switch (jsondata.MetaType) {
        case 'TargetPoint':
          drawPointsFromGeoJSONArray(window.viewer, jsondata.data, "点");
          break;
        case 'DrawLine2':
          drawPointsFromGeoJSONArray(window.viewer, jsondata.data, "线");
          break;
        case 'DrawLine1':
          drawPointsFromGeoJSONArray(window.viewer, jsondata.data, "测向线");
          break;
        case 'DrawEllipse2':
          drawPointsFromGeoJSONArray(window.viewer, jsondata.data, "圆");
          break;
        case 'DrawPolygon':
          drawPointsFromGeoJSONArray(window.viewer, jsondata.data, "多边形");
          break;

        case 'DrawEllipse1':
          drawPointsFromGeoJSONArray(window.viewer, jsondata.data, "椭圆");
          break;
        case 'DrawEllipse3':

          break;
        case 'DrawSectorRing2':
          drawPointsFromGeoJSONArray(window.viewer, jsondata.data, "扇环");
          break;
        case 'DrawSector1':
          drawPointsFromGeoJSONArray(window.viewer, jsondata.data, "扇形");
          break;
      }
      getLayerapi()
    }
  },
    { deep: true }
  );

});

// const pointarr = ref([]);
const Layerdatas = []

const getLayerapi = async () => {
  const res = await getLayer()
  // 递归函数，用于收集所有有 KeyValue 的节点
  const collectKeyValueNodes = (nodes) => {
    let result = []
    if (!nodes) return result
    for (const node of nodes) {
      if (node.KeyValue) {
        result.push(node)
      }
      if (node.Children && node.Children.length > 0) {
        result = result.concat(collectKeyValueNodes(node.Children))
      }
    }
    return result
  }
  Layerdatas.value = collectKeyValueNodes(res.data)
}


const getPointapi = async () => {
  const { data } = await getPoint();

  drawPointsFromGeoJSONArray(window.viewer, data, "点");
};

const getDrawLine2api = async () => {
  const { data } = await getDrawLine2();

  drawPointsFromGeoJSONArray(window.viewer, data, "线");
};

const getDrawLine1api = async () => {
  const { data } = await getDrawLine1();

  drawPointsFromGeoJSONArray(window.viewer, data, "测向线");
};

const getCircleapi = async () => {

  const { data } = await getCircle()

  drawPointsFromGeoJSONArray(window.viewer, data, "圆");
}
const getEllipseapi = async () => {
  const { data } = await getEllipse()
  drawPointsFromGeoJSONArray(window.viewer, data, "椭圆");
}
const getSectorapi = async () => {

  const { data } = await getSector()

  drawPointsFromGeoJSONArray(window.viewer, data, "扇形");
}
const getSectorRingapi = async () => {

  const { data } = await getSectorRing()

  drawPointsFromGeoJSONArray(window.viewer, data, "扇环");
}

const showTrackTable = ref(false);
const TrackTableData = ref(null);

const getTrackLineapi = async () => {
  const { data } = await getTrackLine2();
  TrackTableData.value = data.features;
  showTrackTable.value = true;
  console.log(TrackTableData.value, "航迹线");
  nextTick(() => {
    setModalStyle("trackTableDialog");
  });
  // drawPointsFromGeoJSONArray(window.viewer, data, "航迹线");
};

//
const getPolygonapi = async () => {
  const { data } = await getPolygon()
  drawPointsFromGeoJSONArray(window.viewer, data, "多边形");
}



//
// let pointDrawTool1 = null;
onBeforeUnmount(() => {
  // 清理轨迹工具和通视分析工具
  clearTrajectory();

  // 销毁标签工具实例
  if (labelTool.value) {
    labelTool.value.destroy();
    labelTool.value = null;
  }

  // 销毁绘图工具实例
  if (pointTools.value) {
    pointTools.value.destroy();
    pointTools.value = null;
  }

  if (editpointTools.value) {
    editpointTools.value.destroy();
    editpointTools.value = null;
  }
  if (sectorRingDrawer.value) {
    sectorRingDrawer.value.destroy();
  }
  if (viewer.value) {
    viewer.value.destroy();
  }

  // 可以根据实际情况添加更多需要清理的事件监听器
  proxy.$mitt.off('Layerdata')
  proxy.$mitt.off('cesiumInitialized')
  proxy.$mitt.off('checkedNodestu')
});

const drawPointsFromGeoJSONArray = (viewer, geoJsonArray, name) => {
  switch (name) {
    case "点":
      const pointDrawTool = new DrawTool(window.viewer, { canEdit: true });
      pointDrawTool.createByGeojson(geoJsonArray, '');
      proxy.$mitt.on('checkedNodestu', (checkedNodes) => {
        handleEntityVisibility(pointDrawTool, checkedNodes, '点');
      })

      proxy.$mitt.on("Layerdata", ((e) => {
        pointDrawTool.getEntityObjArr().forEach((obj) => {
          if (obj.attr.formdata.KeyValue == e.KeyValue) {
            obj.entity.show = true
            pointDrawTool.zoomToByObjId(obj.objId)
            pointfrom.value.LayerName = e.LayerName
            pointDrawTool.startEditOne(obj)
          }
        })
      }));

      Layerdatas.value.forEach((item) => {
        pointDrawTool.getEntityObjArr().forEach((obj) => {
          if (obj.attr.formdata.KeyValue == item.KeyValue) {
            obj.entity.show = false
          }
        })
      })
      editstatus(pointDrawTool, "点");
      break;
    case "线":

      const lineDrawTool = new DrawTool(window.viewer, { canEdit: true });


      lineDrawTool.createByGeojson(geoJsonArray, '');

      proxy.$mitt.on('checkedNodestu', (checkedNodes) => {
        handleEntityVisibility(lineDrawTool, checkedNodes, '线');
      })
      proxy.$mitt.on("Layerdata", ((e) => {
        lineDrawTool.getEntityObjArr().forEach((obj) => {
          if (obj.attr.formdata.KeyValue == e.KeyValue) {
            obj.entity.show = true
            lineDrawTool.zoomToByObjId(obj.objId)
            polylinefrom.value.LayerName = e.LayerName
            lineDrawTool.startEditOne(obj)
          }
        })
      }));
      Layerdatas.value.forEach((item) => {
        lineDrawTool.getEntityObjArr().forEach((obj) => {
          if (obj.attr.formdata.KeyValue == item.KeyValue) {
            obj.entity.show = false
          }
        })
      })
      editstatus(lineDrawTool, "线");
      break;
    case "测向线":
      const measureAzimutht = new MeasureAzimutht(viewer, {
        style: {
          // 你可以在这里设置绘制样式
        },
        promptStyle: {
          show: true,
        },
      });
      measureAzimutht.createByGeojson(geoJsonArray);
      // proxy.$mitt.on("Layerdata", ((e) => {
      //   measureAzimutht.getAllInstances().forEach((obj) => {
      //     if (obj.attr?.formdata?.KeyValue == e.KeyValue) {
      //       console.log('测向线')
      //     }
      //   })
      // }));
      break;
    case "航迹线":
      const pointDrawToolline = new MotionTrajectory(
        window.viewer,
        geoJsonArray,
        boatModel
      );
      pointDrawToolline.initLocus();
      proxy.$mitt.on("Layerdata", ((e) => {
        pointDrawToolline.getEntityObjArr().forEach((obj) => {
          if (obj.attr.formdata.KeyValue == e.KeyValue) {
            console.log('航迹线')
          }
        })
      }));
      break;
    case "多边形":
      const polygonDrawTool = new DrawTool(window.viewer, { canEdit: true });

      polygonDrawTool.createByGeojson(geoJsonArray, '');

      proxy.$mitt.on('checkedNodestu', (checkedNodes) => {
        handleEntityVisibility(polygonDrawTool, checkedNodes, '多边形');
      })
      proxy.$mitt.on("Layerdata", ((e) => {
        polygonDrawTool.getEntityObjArr().forEach((obj) => {
          if (obj.attr.formdata.KeyValue == e.KeyValue) {
            obj.entity.show = true
            polygonDrawTool.zoomToByObjId(obj.objId)
            polygonfrom.value.LayerName = e.LayerName

            polygonDrawTool.startEditOne(obj)
          }
        })
      }));

      Layerdatas.value.forEach((item) => {
        polygonDrawTool.getEntityObjArr().forEach((obj) => {
          if (obj.attr.formdata.KeyValue == item.KeyValue) {
            obj.entity.show = false
            obj.polyline.show = false

          }
        })
      })
      editstatus(polygonDrawTool, "多边形");
      break;
    case "圆":
      const circleDrawTool = new DrawTool(window.viewer, { canEdit: true });

      circleDrawTool.createByGeojson(geoJsonArray, '');

      proxy.$mitt.on('checkedNodestu', (checkedNodes) => {
        handleEntityVisibility(circleDrawTool, checkedNodes, '圆');
      })

      proxy.$mitt.on("Layerdata", ((e) => {
        circleDrawTool.getEntityObjArr().forEach((obj) => {
          if (obj.attr.formdata.KeyValue == e.KeyValue) {
            obj.entity.show = true
            circleDrawTool.zoomToByObjId(obj.objId)
            circularfrom.value.LayerName = e.LayerName

            circleDrawTool.startEditOne(obj)

          }
        })
      }));

      Layerdatas.value.forEach((item) => {
        circleDrawTool.getEntityObjArr().forEach((obj) => {
          if (obj.attr.formdata.KeyValue == item.KeyValue) {
            obj.entity.show = false
          }
        })
      })
      editstatus(circleDrawTool, "圆");
      break;
    case "椭圆":
      const ellipseDrawTool = new DrawTool(window.viewer, { canEdit: true });

      ellipseDrawTool.createByGeojson(geoJsonArray, '');

      proxy.$mitt.on('checkedNodestu', (checkedNodes) => {
        handleEntityVisibility(ellipseDrawTool, checkedNodes, '椭圆');
      })
      proxy.$mitt.on("Layerdata", ((e) => {
        ellipseDrawTool.getEntityObjArr().forEach((obj) => {
          if (obj.attr.formdata.KeyValue == e.KeyValue) {
            obj.entity.show = true
            ellipseDrawTool.zoomToByObjId(obj.objId)
            ellipsefrom.value.LayerName = e.LayerName

            ellipseDrawTool.startEditOne(obj)
          }
        })
      }));

      Layerdatas.value.forEach((item) => {
        ellipseDrawTool.getEntityObjArr().forEach((obj) => {
          // console.log(obj)
          if (obj.attr.formdata.KeyValue == item.KeyValue) {
            obj.entity.show = false
          }
        })
      })
      editstatus(ellipseDrawTool, "椭圆");
      break;

    case "扇形":
      const sectorDrawTool = new DrawTool(window.viewer, { canEdit: true });

      sectorDrawTool.createByGeojson(geoJsonArray, '');

      proxy.$mitt.on('checkedNodestu', (checkedNodes) => {
        handleEntityVisibility(sectorDrawTool, checkedNodes, '扇形');
      })

      proxy.$mitt.on("Layerdata", ((e) => {
        sectorDrawTool.getEntityObjArr().forEach((obj) => {
          if (obj.attr.formdata.KeyValue == e.KeyValue) {
            obj.entity.show = true
            sectorDrawTool.zoomToByObjId(obj.objId)
            sectorfrom.value.LayerName = e.LayerName

            sectorDrawTool.startEditOne(obj)
          }
        })
      }));

      Layerdatas.value.forEach((item) => {
        sectorDrawTool.getEntityObjArr().forEach((obj) => {

          if (obj.attr.formdata.KeyValue == item.KeyValue) {
            obj.setVisible(false);
          }
        })
      })


      editstatus(sectorDrawTool, "扇形");


      break;


    case "扇环":
      const sectorRingDrawTool = new DrawTool(window.viewer, { canEdit: true });

      sectorRingDrawTool.createByGeojson(geoJsonArray, '');

      proxy.$mitt.on('checkedNodestu', (checkedNodes) => {
        handleEntityVisibility(sectorRingDrawTool, checkedNodes, '扇环');
      })

      proxy.$mitt.on("Layerdata", ((e) => {
        sectorRingDrawTool.getEntityObjArr().forEach((obj) => {
          if (obj.attr.formdata.KeyValue == e.KeyValue) {
            obj.entity.show = true
            sectorRingDrawTool.zoomToByObjId(obj.objId)
            sectorfrom.value.LayerName = e.LayerName

            sectorRingDrawTool.startEditOne(obj)
          }
        })
      }));

      Layerdatas.value.forEach((item) => {
        sectorRingDrawTool.getEntityObjArr().forEach((obj) => {

          if (obj.attr.formdata.KeyValue == item.KeyValue) {
            obj.setVisible(false);
          }
        })
      })


      editstatus(sectorRingDrawTool, "扇环");


      break;
  }




};
const treeData = ref(null)
//封装编辑
const editstatus = (pointDrawTool, is, str, tree) => {
  editpointTools.value = pointDrawTool;
  treeData.value = tree
  switch (is) {
    case "点":
      pointDrawTool.on("editing", (entityObj, entity) => {
        console.log("正在编辑");
        entityData.value = entityObj;
        drawPointfrom(entityObj, pointfrom.value, tree);
      });

      pointDrawTool.on("endEdit", (entityObj, entity) => {
        console.log("结束编辑");
        isponit.value = false;
        // drawPointfrom(entityObj, pointfrom.value)
        showDrawDialog.value = false;
        if (pointTools.value) {
          pointDrawTool.removeOne(pointTools.value);
        }
      });

      pointDrawTool.on("startEdit", (entityObj, entity) => {
        console.log("开始编辑");
        entityData.value = entityObj;
        editpointTools.value = pointDrawTool;
        if (str == "开始") {
          isponit.value = false;
          drawPointfrom(entityObj, pointfrom.value, "1", tree);
        } else {
          isponit.value = true;
          drawPointfrom(entityObj, pointfrom.value, tree);
        }
      });
      break;
    case "线":
      pointDrawTool.on("editing", (entityObj, entity) => {
        console.log("正在编辑");
        entityData.value = entityObj;
        editpointTools.value = pointDrawTool;
        drawPolylinefrom(entityObj, polylinefrom.value, tree);
      });

      pointDrawTool.on("endEdit", (entityObj, entity) => {
        console.log("结束编辑");
        // drawPolylinefrom(entityObj, polylinefrom.value);
        isponit.value = false;
        editpointTools.value = pointDrawTool;
        showDrawPolylineDialog.value = false;
        if (pointTools.value) {
          pointDrawTool.removeOne(pointTools.value);
        }
      });
      pointDrawTool.on("startEdit", (entityObj, entity) => {
        console.log("开始编辑", entityObj);
        entityData.value = entityObj;
        editpointTools.value = pointDrawTool;
        console.log('editpointTools.value = pointDrawTool;', editpointTools.value, pointDrawTool)
        if (str == "开始") {
          isponit.value = false;
        } else {
          isponit.value = true;
        }
        drawPolylinefrom(entityObj, polylinefrom.value, tree);
      });
      break;

    case '多边形':
      pointDrawTool.on("editing", (entityObj, entity) => {
        console.log("正在编辑");
        entityData.value = entityObj;
        drawPolygonfrom(entityObj, polygonfrom.value, tree);
      });

      pointDrawTool.on("endEdit", (entityObj, entity) => {
        console.log("结束编辑");
        isponit.value = false;
        showDrawpolygonDialog.value = false;
        if (pointTools.value) {
          pointDrawTool.removeOne(pointTools.value);
        }
      });

      pointDrawTool.on("startEdit", (entityObj, entity) => {
        console.log("开始编辑");
        entityData.value = entityObj;
        editpointTools.value = pointDrawTool;
        if (str == "开始") {
          isponit.value = false;

        } else {
          isponit.value = true;

        }
        drawPolygonfrom(entityObj, polygonfrom.value, tree);
      });
      break;

    case '圆':
      pointDrawTool.on("editing", (entityObj, entity) => {
        console.log("正在编辑");
        entityData.value = entityObj;
        drawcircularfrom(entityObj, circularfrom.value, tree);
      });

      pointDrawTool.on("endEdit", (entityObj, entity) => {
        console.log("结束编辑");
        isponit.value = false;
        showDrawcircularDialog.value = false;
        if (pointTools.value) {
          pointDrawTool.removeOne(pointTools.value);
        }
      });

      pointDrawTool.on("startEdit", (entityObj, entity) => {
        console.log("开始编辑");
        entityData.value = entityObj;
        editpointTools.value = pointDrawTool;
        if (str == "开始") {
          isponit.value = false;

        } else {
          isponit.value = true;

        }
        drawcircularfrom(entityObj, circularfrom.value, tree);
      });
      break;
    case '椭圆':
      pointDrawTool.on("editing", (entityObj, entity) => {
        console.log("正在编辑");
        entityData.value = entityObj;

        drawellipsefrom(entityObj, ellipsefrom.value, tree);
      });

      pointDrawTool.on("endEdit", (entityObj, entity) => {
        console.log("结束编辑");
        isponit.value = false;
        showDrawEllipseDialog.value = false;
        if (pointTools.value) {
          pointDrawTool.removeOne(pointTools.value);
        }
      });

      pointDrawTool.on("startEdit", (entityObj, entity) => {
        console.log("开始编辑", entityObj);
        entityData.value = entityObj;
        editpointTools.value = pointDrawTool;
        if (str == "开始") {
          isponit.value = false;

        } else {
          isponit.value = true;
        }
        drawellipsefrom(entityObj, ellipsefrom.value, tree);
      });
      break;
    case '扇形':
      pointDrawTool.on("editing", (entityObj, entity) => {
        console.log("正在编辑", entityObj);
        entityData.value = entityObj;
        drawsectorfrom(entityObj, sectorfrom.value, tree);
      });

      pointDrawTool.on("endEdit", (entityObj, entity) => {
        console.log("结束编辑");
        isponit.value = false;
        showDrawSectorDialog.value = false;
        if (pointTools.value) {
          pointDrawTool.removeOne(pointTools.value);
        }
      });

      pointDrawTool.on("startEdit", (entityObj, entity) => {
        console.log("开始编辑扇", entityObj);
        entityData.value = entityObj;
        editpointTools.value = pointDrawTool;
        if (str == "开始") {
          isponit.value = false;
        } else {
          isponit.value = true;
        }
        drawsectorfrom(entityObj, sectorfrom.value, tree);
      });
      break;
    case '扇环':
      pointDrawTool.on("editing", (entityObj, entity) => {
        console.log("正在编辑", entityObj);
        entityData.value = entityObj;
        drawsectorringfrom(entityObj, sectorRingfrom.value, tree);
      });
      pointDrawTool.on("endEdit", (entityObj, entity) => {
        console.log("结束编辑");
        isponit.value = false;
        showDrawSectorRingDialog.value = false;
        if (pointTools.value) {
          console.log('pointTools.value = pointDrawTool;', pointTools.value)
          pointDrawTool.removeOne(pointTools.value);
        }
      });
      pointDrawTool.on("startEdit", (entityObj, entity) => {
        console.log("开始编辑扇环", entityObj);
        entityData.value = entityObj;
        editpointTools.value = pointDrawTool;
        if (str == "开始") {
          isponit.value = false;
        } else {
          isponit.value = true;
        }
        drawsectorringfrom(entityObj, sectorRingfrom.value, tree);
      });
      break;
    case '文字':
      pointDrawTool.on("editing", (entityObj, entity) => {
        console.log("正在编辑");
        entityData.value = entityObj;
        drawlabelfrom(entityObj, labelfrom.value);
      });

      pointDrawTool.on("endEdit", (entityObj, entity) => {
        console.log("结束编辑");
        isponit.value = false;
        showDrawLableDialog.value = false;
        if (pointTools.value) {
          pointDrawTool.removeOne(pointTools.value);
        }
      });

      pointDrawTool.on("startEdit", (entityObj, entity) => {
        console.log("开始编辑");
        entityData.value = entityObj;
        editpointTools.value = pointDrawTool;
        if (str == "开始") {
          isponit.value = false;

        } else {
          isponit.value = true;

        }
        drawlabelfrom(entityObj, labelfrom.value);
      });
      break;

  }
};

//
const scaleFactor = ref(1); // 存储当前缩放倍数

//=================================
const objId = ref(null);
//点
const drawPointfrom = (data, from, str = "编辑", tree) => {
  objId.value = data.objId;
  let lonlatalt = data.getPositions(true);
  from.StartP = Point3D(lonlatalt);
  const linestyle = entityData.value.getStyle();
  from.KeyValue = data.attr?.formdata?.KeyValue;
  from.Icon = JIcon(linestyle, "", str, '点');
  from.LayerID = ''

  if (tree) {
    from.LayerName = tree.treedata.LayerName
    from.LayerID = tree.treedata.id;
  } else {
    from.LayerName = data.attr.formdata?.LayerName || from.LayerName
  }
  console.log("点返回", data, from);
  showDrawDialog.value = true;
  nextTick(() => {
    setModalStyle("drawPointDialog");
  });
};


const changepointfrom = (e) => {
  console.log("点返回", e);
  const pointDrawTool = new DrawTool(window.viewer, { canEdit: true });
  const newPosition = Cesium.Cartesian3.fromDegrees(
    Number(e.StartP.Lon),
    Number(e.StartP.Lat),
    Number(e.StartP.Alt)
  );

  entityData.value.position = newPosition;
  entityData.value.entity.position.setValue(newPosition);

  let style;
  if (e.Icon.ColorData != "no") {
    style = {
      colorAlpha:
        iscolor(e.Icon.ColorData) == "rgb"
          ? 1
          : extractAlphaFromRgba(e.Icon.ColorData),
      color: e.Icon.ColorData,
      pixelSize: e.Icon.IconSize,
      // outlineWidth: 2, // 可根据实际情况调整
      // outlineColor: "#0000ff", // 可根据实际情况调整
      // outlineColorAlpha: 0.6, // 可根据实际情况调整
      heightReference: 1, // 可根据实际情况调整
    };
  } else {
    style = {
      colorAlpha: e.Icon.ColorData.alpha,
      color: `rgba(${e.Icon.ColorData.red},${e.Icon.ColorData.green},${e.Icon.ColorData.blue},${e.Icon.ColorData.alpha})`,
      pixelSize: e.Icon.IconSize,
      // outlineWidth: 2, // 可根据实际情况调整
      // outlineColor: "#0000ff", // 可根据实际情况调整
      // outlineColorAlpha: 0.6, // 可根据实际情况调整
      heightReference: 1, // 可根据实际情况调整
    };
  }

  entityData.value.style = style;

  // 更改颜色
  entityData.value.setStyle(style);
  //
  editstatus(pointDrawTool, "点");
};

// 线
const drawPolylinefrom = (data, from, tree) => {
  console.log("线from", data, from);
  if (isponit.value) {
    from.id = data.attr.formdata.id;
  }
  if (tree) {
    from.LayerName = tree.treedata.LayerName
    from.LayerID = tree.treedata.id;
  } else {
    from.LayerName = data.attr.formdata?.LayerName || from.LayerName
  }
  from.KeyValue = data.attr?.formdata?.KeyValue;
  from.Leixing = '线'
  let poarr = [];
  data.getPositions(true).forEach((e) => {
    poarr.push(Point3D(e));
  });
  from.Point = poarr;

  const linestyle = entityData.value.getStyle();
  // {
  //     "material": "common",
  //     "colorAlpha": 1,
  //     "color": "#ffff00",
  //     "width": 3,
  //     "clampToGround": true
  // }
  console.log("linestyle", linestyle);
  from.LineStyle = LineStyle(linestyle);
  showDrawPolylineDialog.value = true;
  nextTick(() => {
    setModalStyle("drawPolylineDialog");
  });
};

const changepolylinefrom = (e) => {
  const pointDrawTool = new DrawTool(window.viewer, { canEdit: true });
  let Pointarr = [];
  e.Point.forEach((ele) => {
    Pointarr.push(
      Cesium.Cartesian3.fromDegrees(
        Number(ele.Lon),
        Number(ele.Lat),
        Number(ele.Alt)
      )
    );
  });
  entityData.value.positions = Pointarr;
  updateControlPoints(entityData.value, Pointarr);
  // debugger
  let style = {
    material: "common",
    colorAlpha: e.LineStyle.LineColor.A / 255,
    color: `rgba(${e.LineStyle.LineColor.R},${e.LineStyle.LineColor.G},${e.LineStyle.LineColor.B},${e.LineStyle.LineColor.A})`,
    width: e.LineStyle.LineWidth,
    clampToGround: true,
  };

  entityData.value.setStyle(style);

  editstatus(pointDrawTool, "线");
};

const updateControlPoints = (polylineObj, newPositions) => {
  if (!polylineObj.controlPoints || polylineObj.controlPoints.length === 0)
    return;

  // 确保控制点数量与新坐标数量一致
  const pointCount = Math.min(
    polylineObj.controlPoints.length,
    newPositions.length
  );
  for (let i = 0; i < pointCount; i++) {
    const controlPoint = polylineObj.controlPoints[i];
    const newPosition = newPositions[i];
    console.log("controlPoint", controlPoint);
    console.log("newPosition", newPosition);
    // 更新控制点的位置
    if (controlPoint.point) {
      controlPoint.position.setValue(newPosition);
    }

    // 记录新位置索引
    controlPoint.wz = i;
  }

  // 处理多余的控制点（如果有）
  if (polylineObj.controlPoints.length > newPositions.length) {
    for (
      let i = newPositions.length;
      i < polylineObj.controlPoints.length;
      i++
    ) {
      polylineObj.viewer.entities.remove(polylineObj.controlPoints[i]);
    }
    polylineObj.controlPoints = polylineObj.controlPoints.slice(
      0,
      newPositions.length
    );
  }
};
// 多边形

const drawPolygonfrom = (data, from, tree) => {
  console.log("多边形from", data, from, data.getPositions(true));
  if (isponit.value) {
    from.id = data.attr.formdata.id;
  }
  if (tree) {
    from.LayerName = tree.treedata.LayerName
    from.LayerID = tree.treedata.id;
  } else {
    from.LayerName = data.attr.formdata?.LayerName || from.LayerName
  }
  from.KeyValue = data.attr?.formdata?.KeyValue;
  from.Leixing = '多边形'
  let poarr = [];
  data.getPositions(true).forEach((e) => {
    poarr.push(Point3D(e));
  });
  from.Point = poarr;

  const linestyle = entityData.value.getStyle();
  console.log("linestyle", linestyle);
  from.Style = Area(linestyle);
  showDrawpolygonDialog.value = true;
  nextTick(() => {
    setModalStyle("drawpolygonDialog");
  });

}
const changepolygonfromcol = (e) => {
  console.log("多边形", e);
  const pointDrawTool = new DrawTool(window.viewer, { canEdit: true });
  let Pointarr = [];

  e.Point.forEach((ele) => {
    Pointarr.push(
      Cesium.Cartesian3.fromDegrees(
        Number(ele.Lon),
        Number(ele.Lat),
        Number(ele.Alt)
      )
    );
  });




  entityData.value.positions = Pointarr;
  updateControlPoints(entityData.value, Pointarr);

  let style = {
    colorAlpha: e.Style.FillColor.A / 255,
    color: e.Style.ColorData,
    fill: true,
    heightReference: 1,
    material: 'common',
    outlineWidth: e.Style.LineWidth,
    outline: e.Style.LineStyle == 0 ? true : false,
    outlineColorAlpha: e.Style.LineColor.A / 255,
    outlineColor: e.Style.lineColorData,
  }

  entityData.value.setStyle(style);

  editstatus(pointDrawTool, "多边形");
};


// 圆
const drawcircularfrom = (data, from, tree) => {
  console.log("圆from", data, from, data.getPositions(true));
  if (isponit.value) {
    from.id = data.attr.formdata.id;
  }
  if (tree) {
    from.LayerName = tree.treedata.LayerName
    from.LayerID = tree.treedata.id;
  } else {
    from.LayerName = data.attr.formdata?.LayerName || from.LayerName
  }

  from.KeyValue = data.attr?.formdata?.KeyValue;
  from.Leixing = '圆'
  let poarr = [];
  data.getPositions(true).forEach((e) => {
    poarr.push(Point3D(e));
  });
  console.log("poarr", poarr);
  from.CenterP = poarr[0];
  from.Radiuslot = poarr[1]
  const linestyle = entityData.value.getStyle();
  console.log("linestyle", linestyle);
  console.log("from", from);
  from.Style = Area(linestyle);
  showDrawcircularDialog.value = true;
  nextTick(() => {
    setModalStyle("drawcircularDialog");
  });

}
const drawellipsefrom = (data, from, tree) => {
  console.log('椭圆', data, from)
  if (isponit.value) {
    from.id = data.attr.formdata.id;
  }
  if (tree) {
    from.LayerName = tree.treedata.LayerName
    from.LayerID = tree.treedata.id;
  } else {
    from.LayerName = data.attr.formdata?.LayerName || from.LayerName
  }
  from.KeyValue = data.attr?.formdata?.KeyValue;
  from.Leixing = '椭圆'
  // data.getPositions(true).forEach((e) => {
  //   poarr.push(Point3D(e));
  // });

  const ellipsoid = Cesium.Ellipsoid.WGS84;
  const cartographic = ellipsoid.cartesianToCartographic(data.center);
  const longitudeRadians = cartographic.longitude;
  const latitudeRadians = cartographic.latitude;
  const height = cartographic.height;
  const longitudeDegrees = Cesium.Math.toDegrees(longitudeRadians);
  const latitudeDegrees = Cesium.Math.toDegrees(latitudeRadians);
  from.CenterP = Point3D([longitudeDegrees, latitudeDegrees, height]);
  from.LongHalfAxis = Number(data.semiMajorAxis)
  from.ShortHalfAxis = Number(data.semiMinorAxis)
  const linestyle = entityData.value.getStyle();
  from.Style = Area(linestyle);
  const rotationRadian = data.rotation; // 弧度
  const rotationDegree = Cesium.Math.toDegrees(rotationRadian); // 转换为角度
  from.Heading = rotationDegree
  console.log('from', from)
  showDrawEllipseDialog.value = true;
  nextTick(() => {
    setModalStyle("drawcirEllipseDialog");
  });
}
const drawsectorfrom = (data, from, tree) => {
  console.log('color', data)
  if (isponit.value) {
    from.id = data.attr.formdata.id;
  }
  if (tree) {
    from.LayerName = tree.treedata.LayerName
    from.LayerID = tree.treedata.id;
  } else {
    from.LayerName = data.attr.formdata?.LayerName || from.LayerName
  }
  from.KeyValue = data.attr?.formdata?.KeyValue;
  from.Leixing = '扇形'
  const center = data.center;
  let poarr = [];
  if (center) {
    const cartographic = Cesium.Cartographic.fromCartesian(center);
    poarr = [Cesium.Math.toDegrees(cartographic.longitude), Cesium.Math.toDegrees(cartographic.latitude), cartographic.height];
    from.CenterP = Point3D(poarr);
  }
  from.Radius = data.radius;
  // 获取起始角度和结束角度
  from.StartAngle = radiansToDegrees(data.startAngle);
  from.EndAngle = radiansToDegrees(data.endAngle);
  const style = data.getStyle();
  console.log('style', style)
  from.Style = Area(style);
  console.log('from', from)
  showDrawSectorDialog.value = true;
  nextTick(() => {
    setModalStyle("drawSectorDialog");
  });
}
const drawsectorringfrom = (data, from, tree) => {
  console.log('data', data)
  if (isponit.value) {
    from.id = data.attr.formdata.id;
  }
  if (tree) {
    from.LayerName = tree.treedata.LayerName
    from.LayerID = tree.treedata.id;
  } else {
    from.LayerName = data.attr.formdata?.LayerName || from.LayerName
  }
  from.KeyValue = data.attr?.formdata?.KeyValue;
  from.Leixing = '扇环'
  const center = data.center;
  let poarr = [];
  if (center) {
    const cartographic = Cesium.Cartographic.fromCartesian(center);
    poarr = [Cesium.Math.toDegrees(cartographic.longitude), Cesium.Math.toDegrees(cartographic.latitude), cartographic.height];
    from.CenterP = Point3D(poarr);
  }
  from.InnerRadius = data.innerRadius;
  from.OuterRadius = data.outerRadius;
  // 获取起始角度和结束角度
  from.StartAngle = radiansToDegrees(data.startAngle);
  from.EndAngle = radiansToDegrees(data.endAngle);
  const style = data.getStyle();
  console.log('style', style)
  from.Style = Area(style);
  console.log('from', from)
  showDrawSectorRingDialog.value = true;
  nextTick(() => {
    setModalStyle("drawSectorRingDialog");
  });
}
const radiansToDegrees = (radians) => {
  return (radians * 180) / Math.PI;
}
const degreesToRadians = (degrees) => {
  return (degrees * Math.PI) / 180;
}
const changecircularfromcol = (e) => {
  console.log("圆", e);
  const pointDrawTool = new DrawTool(window.viewer, { canEdit: true });
  let Pointarr = [];


  Pointarr.push(
    Cesium.Cartesian3.fromDegrees(
      Number(e.CenterP.Lon),
      Number(e.CenterP.Lat),
      Number(e.CenterP.Alt)
    )
  );
  Pointarr.push(
    Cesium.Cartesian3.fromDegrees(
      Number(e.Radiuslot.Lon),
      Number(e.Radiuslot.Lat),
      Number(e.Radiuslot.Alt)
    )
  );

  // 更新中心点坐标
  entityData.value.position = Pointarr[0];
  entityData.value.entity.position.setValue(Pointarr[0]);
  entityData.value.centerPoint.position.setValue(Pointarr[0]);

  // 更新半径点坐标并重新计算半径
  entityData.value.floatPosition = Pointarr[1];
  entityData.value.floatPoint.position.setValue(Pointarr[1]);
  entityData.value.radius = Cesium.Cartesian3.distance(Pointarr[0], Pointarr[1]);
  let style = {
    colorAlpha: e.Style.FillColor.A / 255,
    color: e.Style.ColorData,
    fill: true,
    heightReference: 1,
    material: 'common',
    outlineWidth: 1,
    outline: false,
    outlineColorAlpha: e.Style.LineColor.A / 255,
    outlineColor: e.Style.lineColorData,
  }

  entityData.value.setStyle(style);

  editstatus(pointDrawTool, "圆");
};
const changeellipsefromcol = (e) => {
  console.log("椭圆", e, entityData.value);
  e.LongHalfAxis = Number(e.LongHalfAxis);
  e.ShortHalfAxis = Number(e.ShortHalfAxis);
  const pointDrawTool = new DrawTool(window.viewer, { canEdit: true });
  const lon = Number(e.CenterP.Lon);
  const lat = Number(e.CenterP.Lat);
  const alt = Number(e.CenterP.Alt);
  const newCenter = Cesium.Cartesian3.fromDegrees(lon, lat, alt);

  // 更新椭圆实体的中心点位置
  entityData.value.center = newCenter;
  entityData.value.entity.position.setValue(newCenter);
  entityData.value.semiMajorAxis = Number(e.LongHalfAxis);
  entityData.value.semiMinorAxis = Number(e.ShortHalfAxis);
  console.log("椭圆", entityData.value);
  // 更新椭圆的旋转角度
  const rotationRadian = Cesium.Math.toRadians(e.Heading);
  entityData.value.rotation = rotationRadian
  // 更新编辑点的位置
  // 中心点
  entityData.value.centerPoint.position.setValue(newCenter);
  const majorAxisVector = new Cesium.Cartesian3();
  Cesium.Cartesian3.multiplyByScalar(
    Cesium.Cartesian3.normalize(
      Cesium.Cartesian3.subtract(entityData.value.majorAxisPosition, entityData.value.center, new Cesium.Cartesian3()),
      majorAxisVector
    ),
    e.LongHalfAxis,
    majorAxisVector
  );
  const newMajorAxisPosition = Cesium.Cartesian3.add(newCenter, majorAxisVector, new Cesium.Cartesian3());
  entityData.value.majorAxisPosition = newMajorAxisPosition;
  entityData.value.majorAxisPoint.position.setValue(newMajorAxisPosition);

  // 短轴端点位置计算
  const minorAxisVector = new Cesium.Cartesian3();
  Cesium.Cartesian3.multiplyByScalar(
    Cesium.Cartesian3.normalize(
      Cesium.Cartesian3.subtract(entityData.value.minorAxisPosition, entityData.value.center, new Cesium.Cartesian3()),
      minorAxisVector
    ),
    e.ShortHalfAxis,
    minorAxisVector
  );
  const newMinorAxisPosition = Cesium.Cartesian3.add(newCenter, minorAxisVector, new Cesium.Cartesian3());
  entityData.value.minorAxisPosition = newMinorAxisPosition;
  entityData.value.minorAxisPoint.position.setValue(newMinorAxisPosition);
  let style = {
    colorAlpha: e.Style.FillColor.A / 255,
    color: e.Style.ColorData,
    fill: true,
    heightReference: 1,
    material: 'common',
    outlineWidth: e.Style.LineWidth,
    outline: false,
    outlineColorAlpha: e.Style.LineColor.A / 255,
    outlineColor: e.Style.lineColorData,
  };
  entityData.value.setStyle(style);
  console.log("entityData", entityData.value);

  editstatus(pointDrawTool, "椭圆");
};
const changesectorfromcol = (e) => {
  // console.log("扇形", e);
  e.StartAngle = Number(e.StartAngle);
  e.StartAngle = Number(e.StartAngle);
  const pointDrawTool = new DrawTool(window.viewer, { canEdit: true });
  const lon = Number(e.CenterP.Lon);
  const lat = Number(e.CenterP.Lat);
  const alt = Number(e.CenterP.Alt);
  const newCenter = Cesium.Cartesian3.fromDegrees(lon, lat, alt);
  // console.log("newCenter", newCenter);

  // 计算中心点的偏移量
  const subtract = Cesium.Cartesian3.subtract(
    newCenter,
    entityData.value.center,
    new Cesium.Cartesian3()
  );
  entityData.value.center = newCenter;
  entityData.value.position = newCenter;
  entityData.value.centerPoint.position.setValue(newCenter);
  // 更新边缘点位置
  entityData.value.edge = Cesium.Cartesian3.add(
    entityData.value.edge,
    subtract,
    new Cesium.Cartesian3()
  );
  entityData.value.edgePoint.position.setValue(entityData.value.edge);
  entityData.value.edgePosition = entityData.value.edge.clone();

  // 更新角度控制点位置
  entityData.value.angle = Cesium.Cartesian3.add(
    entityData.value.angle,
    subtract,
    new Cesium.Cartesian3()
  );
  entityData.value.anglePoint.position.setValue(entityData.value.angle);
  entityData.value.anglePosition = entityData.value.angle.clone();

  // 重新计算半径
  entityData.value.radius = Cesium.Cartesian3.distance(entityData.value.center, entityData.value.edge);

  entityData.value.startAngle = degreesToRadians(Number(e.StartAngle));
  entityData.value.endAngle = degreesToRadians(Number(e.EndAngle));

  entityData.value.radius = Number(e.Radius);
  // 更新扇形实体


  // console.log("扇形", entityData.value);
  // 中心点


  let style = {
    colorAlpha: e.Style.FillColor.A / 255,
    color: e.Style.ColorData,
    fill: true,
    heightReference: 1,
    material: 'common',
    outlineWidth: e.Style.LineWidth,
    outline: false,
    outlineColorAlpha: e.Style.LineColor.A / 255,
    outlineColor: e.Style.lineColorData,
  };
  entityData.value.setStyle(style);
  // console.log("entityData", entityData.value);
  entityData.value.entity = entityData.value.createSector();
  // editstatus(pointDrawTool, "扇形");
};
const changesectorringfromcol = (e) => {

  const pointDrawTool = new DrawTool(window.viewer, { canEdit: true });

  // 更新中心点位置
  const lon = Number(e.CenterP.Lon);
  const lat = Number(e.CenterP.Lat);
  const alt = Number(e.CenterP.Alt);
  const newCenter = Cesium.Cartesian3.fromDegrees(lon, lat, alt);

  // 检查中心点是否已定义


  // 计算中心点的偏移量
  const subtract = Cesium.Cartesian3.subtract(
    newCenter,
    entityData.value.center,
    new Cesium.Cartesian3()
  );
  console.log("newCenter", newCenter);
  console.log("entityData.value", entityData.value);
  // 更新中心点
  entityData.value.center = newCenter;
  entityData.value.entity.position = newCenter;
  entityData.value.centerPoint.position.setValue(newCenter);

  // 更新控制点位置（仅在中心点已存在时执行）
  // 检查各个控制点是否已定义
  if (entityData.value.innerStartPoint) {
    // 更新内半径点位置
    const newInnerStart = Cesium.Cartesian3.add(
      entityData.value.innerStartPoint.position.getValue(Cesium.JulianDate.now()),
      subtract,
      new Cesium.Cartesian3()
    );
    entityData.value.innerStartPoint.position.setValue(newInnerStart);
    console.log("innerStart updated", newInnerStart);
  }

  if (entityData.value.outerStartPoint) {
    // 更新外半径点位置
    const newOuterStart = Cesium.Cartesian3.add(
      entityData.value.outerStartPoint.position.getValue(Cesium.JulianDate.now()),
      subtract,
      new Cesium.Cartesian3()
    );
    entityData.value.outerStartPoint.position.setValue(newOuterStart);
    console.log("outerStart updated", newOuterStart);
  }

  if (entityData.value.outerEndPoint) {
    // 更新外半径结束点位置
    const newOuterEnd = Cesium.Cartesian3.add(
      entityData.value.outerEndPoint.position.getValue(Cesium.JulianDate.now()),
      subtract,
      new Cesium.Cartesian3()
    );
    entityData.value.outerEndPoint.position.setValue(newOuterEnd);
    console.log("outerEnd updated", newOuterEnd);
  }

  // 更新内半径和外半径
  entityData.value.innerRadius = Number(e.InnerRadius);
  entityData.value.outerRadius = Number(e.OuterRadius);

  // 更新角度
  entityData.value.startAngle = degreesToRadians(Number(e.StartAngle));
  entityData.value.endAngle = degreesToRadians(Number(e.EndAngle));

  // 确保角度在正确范围内
  if (entityData.value.endAngle < entityData.value.startAngle) {
    entityData.value.endAngle += Cesium.Math.TWO_PI;
  }
  console.log("扇环", e);

  // 设置样式
  let style = {
    colorAlpha: e.Style.FillColor.A / 255,
    innerRadius: e.InnerRadius,
    outerRadius: e.OuterRadius,
    startAngle: e.StartAngle,
    endAngle: e.EndAngle,
    color: e.Style.ColorData,
    material: 'common',
    outlineWidth: e.Style.LineWidth,
    outline: true,
    outlineColorAlpha: e.Style.LineColor.A / 255,
    outlineColor: typeof e.Style.lineColor === 'string' ? e.Style.lineColor : e.Style.LineColordata,
  };
  entityData.value.setStyle(style);
  entityData.value.entity = entityData.value.createSectorRingEntity();
  console.log("扇环更新完成", entityData.value);
  // editstatus(pointDrawTool, "扇环");
};


// 文字
const drawlabelfrom = (data, from) => {
  console.log("文字from", data, from, data.getPositions(true));
  if (isponit.value) {
    from.id = data.attr.formdata.id;
  }
  from.Leixing = '文字'
  from.StartP = Point3D(data.getPositions(true))

  // 假设 window.viewer 是 Cesium Viewer 实例

  const cartesian3 = Cesium.Cartesian3.fromDegrees(data.getPositions(true)[0], data.getPositions(true)[1], data.getPositions(true)[2]);
  const canvasPosition = window.viewer.scene.cartesianToCanvasCoordinates(cartesian3);

  from.StartX = canvasPosition.x;
  from.StartY = canvasPosition.y;

  from.KeyValue = data.attr?.formdata?.KeyValue;

  const linestyle = entityData.value.getStyle();
  from.Title = linestyle.text
  from.FontStyle = FontStyle(linestyle, '字')
  // console.log(linestyle)


  showDrawLableDialog.value = true;
  nextTick(() => {
    setModalStyle("drawLableDialog");
  });

}


const changelabelfromcol = (e) => {
  const viewer = window.viewer;
  const scene = viewer.scene;
  const camera = viewer.camera;
  console.log('字', e);
  const pointDrawTool = new DrawTool(window.viewer, { canEdit: true });
  const screenX = Number(e.StartX);
  const screenY = Number(e.StartY);
  const screenPosition = new Cesium.Cartesian2(screenX, screenY);
  const height = Number(e.StartP?.Alt) || 100;
  const ray = camera.getPickRay(screenPosition);
  const globe = scene.globe;
  let cartesian;
  cartesian = globe.pick(ray, scene);
  if (!cartesian) {
    // 备选方法：使用射线与指定高度的水平面相交
    const plane = new Cesium.Plane(Cesium.Cartesian3.UNIT_Z, -height);
    const intersection = Cesium.IntersectionTests.rayPlane(ray, plane);

    if (intersection) {
      cartesian = Cesium.Cartesian3.add(
        ray.origin,
        Cesium.Cartesian3.multiplyByScalar(
          ray.direction,
          intersection,
          new Cesium.Cartesian3()
        ),
        new Cesium.Cartesian3()
      );
    } else {
      console.error('无法从屏幕坐标计算位置');
      return;
    }

    // 根据 e.StartP 中的经纬度和高度信息创建 Cartesian3 对象


    // let style = {
    //   // fillColorAlpha: e.FontStyle.ForeColor.A,
    //   // fillColor: e.FontStyle.ForeColordata,
    //   // showBackground: true,
    //   // backgroundColorAlpha: e.FontStyle.BackColor.A,
    //   // backgroundColor: e.FontStyle.BackColordata,
    //   // heightReference: 0,
    //   pixelOffset: {
    //     x: Number(e.StartX),
    //     y: Number(e.StartY)
    //   },
    //   // scale: e.FontStyle.FontSize,
    //   // text: e.Title
    // };

    entityData.value.setStyle(style);
    editstatus(pointDrawTool, "文字");
  }
  // 将世界坐标转换为经纬度（弧度）
  const cartographic = Cesium.Cartographic.fromCartesian(cartesian);

  // 转换为角度表示的经纬度
  const longitude = Cesium.Math.toDegrees(cartographic.longitude);
  const latitude = Cesium.Math.toDegrees(cartographic.latitude);

  console.log('转换后的经纬度:', { longitude, latitude, height });

  // 更新文字位置（使用计算出的经纬度和高度）
  const newPosition = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
  entityData.value.setPosition(newPosition);

  // 样式设置（保持原有逻辑不变）
  const fillAlpha = Math.max(0, Math.min(1, e.FontStyle.ForeColor.A / 255));
  const bgAlpha = Math.max(0, Math.min(1, e.FontStyle.BackColor.A / 255));
  const fontSize = e.FontStyle.FontSize || 2;

  let style = {
    fillColorAlpha: fillAlpha,
    fillColor: e.FontStyle.ForeColordata,
    showBackground: true,
    backgroundColorAlpha: bgAlpha,
    backgroundColor: e.FontStyle.BackColordata,
    heightReference: 0,
    pixelOffset: { x: 0, y: 0 }, // 像素偏移已在屏幕坐标中处理
    scale: fontSize,
    text: e.Title
  };

  entityData.value.setStyle(style);
  editstatus(pointDrawTool, "文字");
}

/**
 * 根据选中节点控制实体显示状态
 * @param {Array} checkedNodes - 选中的节点数组
 */
const handleEntityVisibility = (pointDrawTool, checkedNodes, type) => {
  if (!window.viewer || !window.viewer.entities) return;

  // 遍历所有实体，根据选中状态设置显示/隐藏
  pointDrawTool.getEntityObjArr().forEach((obj) => {
    // 检查当前实体是否在选中节点中
    const isChecked = checkedNodes.some(item => obj.attr.formdata.KeyValue === item.KeyValue);

    // 修改这里：使用 setVisible 方法
    obj.setVisible(isChecked);
    if (type == '多边形') {
      obj.polyline.show = isChecked
    }
  });

  pointDrawTool.getEntityObjArr().forEach((obj) => {
    checkedNodes.forEach((item) => {
      if (obj.attr.formdata.KeyValue == item.KeyValue) {
        // 修改这里：使用 setVisible 方法
        obj.setVisible(true);
        if (type == '多边形') {
          obj.polyline.show = true
        }
      }
    })
  })
};

//----------------------------------------------------------
// 定位
const showdiopositi = ref(false);

// 区域截图
const isRegionScreenshotActive = ref(true);
const cleanupScreenshotHandler = ref(null);
const initScreenshot = (viewer) => {
  if (!viewer) return;

  // 设置截图时的鼠标样式
  const originalCursor = viewer.canvas.style.cursor;
  viewer.canvas.style.cursor = "crosshair"; // 设置为十字准星样式
  // 禁用区域截图功能，防止重复触发
  isRegionScreenshotActive.value = false;

  const selectionBox = document.createElement("div");
  selectionBox.style.position = "absolute";
  selectionBox.style.border = "2px dashed red";
  selectionBox.style.backgroundColor = "rgba(0,0,0,0.2)";
  selectionBox.style.display = "none";
  selectionBox.style.zIndex = "9999";
  document.body.appendChild(selectionBox);

  let startX, startY;
  let isSelecting = false;

  const rect = viewer.canvas.getBoundingClientRect();
  const dpr = window.devicePixelRatio || 1;

  const handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);

  // 修改清理函数
  cleanupScreenshotHandler.value = () => {
    try {
      // 先移除事件监听
      handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOWN);
      handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_UP);

      // 延迟销毁，确保事件处理完成
      setTimeout(() => {
        if (!handler.isDestroyed()) {
          handler.destroy();
        }
      }, 100);
    } catch (e) {
      console.warn("清理截图处理器时出错:", e);
    }

    viewer.canvas.style.cursor = originalCursor;
    if (selectionBox.parentNode) {
      document.body.removeChild(selectionBox);
    }
    isRegionScreenshotActive.value = true;
  };

  handler.setInputAction((movement) => {
    isSelecting = true;

    startX = movement.position.x;
    startY = movement.position.y;

    const controller = viewer.scene.screenSpaceCameraController;
    controller.enableRotate = false;
    controller.enableTranslate = false;
    controller.enableZoom = false;
    controller.enableTilt = false;
    controller.enableLook = false;

    selectionBox.style.left = `${startX + rect.left}px`;
    selectionBox.style.top = `${startY + rect.top}px`;
    selectionBox.style.width = "0px";
    selectionBox.style.height = "0px";
    selectionBox.style.display = "block";
  }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

  handler.setInputAction((movement) => {
    if (!isSelecting) return;

    const currentX = movement.endPosition.x;
    const currentY = movement.endPosition.y;

    const left = Math.min(startX, currentX);
    const top = Math.min(startY, currentY);
    const width = Math.abs(currentX - startX);
    const height = Math.abs(currentY - startY);

    selectionBox.style.left = `${left + rect.left}px`;
    selectionBox.style.top = `${top + rect.top}px`;
    selectionBox.style.width = `${width}px`;
    selectionBox.style.height = `${height}px`;
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  handler.setInputAction(() => {
    if (!isSelecting) return;
    isSelecting = false;

    // 恢复原始鼠标样式
    viewer.canvas.style.cursor = originalCursor;

    const controller = viewer.scene.screenSpaceCameraController;
    controller.enableRotate = true;
    controller.enableTranslate = true;
    controller.enableZoom = true;
    controller.enableTilt = true;
    controller.enableLook = true;

    const boxRect = selectionBox.getBoundingClientRect();

    const sx_css = boxRect.left - rect.left;
    const sy_css = boxRect.top - rect.top;
    const sw_css = boxRect.width;
    const sh_css = boxRect.height;

    const sx = sx_css * dpr;
    const sy = sy_css * dpr;
    const sw = sw_css * dpr;
    const sh = sh_css * dpr;

    if (sw > 10 && sh > 10) {
      const removeListener = viewer.scene.postRender.addEventListener(() => {
        removeListener();

        const dataURL = viewer.canvas.toDataURL("image/png");

        const image = new Image();
        image.onload = () => {
          const tempCanvas = document.createElement("canvas");
          tempCanvas.width = sw;
          tempCanvas.height = sh;
          const ctx = tempCanvas.getContext("2d");

          ctx.drawImage(image, sx, sy, sw, sh, 0, 0, sw, sh);

          tempCanvas.toBlob((blob) => {
            if (blob) {
              const link = document.createElement("a");
              link.href = URL.createObjectURL(blob);
              link.download = "区域截图.png";
              link.click();
              URL.revokeObjectURL(link.href);
            }
          }, "image/png");
        };
        image.src = dataURL;
      });

      viewer.scene.render();
    }

    selectionBox.style.display = "none";

    // 截图完成后，清理事件和DOM，恢复截图功能
    if (cleanupScreenshotHandler.value) {
      cleanupScreenshotHandler.value(); // 直接调用清理函数
      cleanupScreenshotHandler.value = null;
    }

    isRegionScreenshotActive.value = true;
    console.log("区域截图功能已恢复");
  }, Cesium.ScreenSpaceEventType.LEFT_UP);
};

// 全屏截图
const captureScreenshot = (viewer) => {
  const scene = viewer.scene;
  return new Promise((resolve, reject) => {
    const removeCallback = scene.postRender.addEventListener(() => {
      removeCallback();
      try {
        const canvas = viewer.scene.canvas;
        canvas.toBlob((blob) => {
          if (blob) {
            resolve(blob);
          } else {
            reject(new Error("Failed to capture screenshot blob"));
          }
        }, "image/png");
      } catch (e) {
        reject(e);
      }
    });
    scene.render(viewer.clock.currentTime);
  });
};

const takeScreenshot = (viewer) => {
  captureScreenshot(viewer)
    .then((blob) => {
      saveAs(blob, `${Date.now()}.png`);
    })
    .catch((error) => {
      console.error("截图失败:", error);
    });
};

const saveAs = (blob, filename) => {
  if (!blob) return;
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    const link = document.createElement("a");
    const url = window.URL.createObjectURL(blob);
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  }
};
// 设置遮罩层样式的方法
const setModalStyle = (id) => {
  const elDialog = document.getElementById(id);
  if (!elDialog) return;

  // 获取弹窗的父节点（可能是遮罩层容器）
  const parentNode = elDialog.parentNode;
  if (!parentNode) return;

  // 设置父节点不响应点击事件
  parentNode.style.pointerEvents = "none";

  // 确保弹窗本身可以接收点击事件
  elDialog.style.pointerEvents = "auto";

  // 尝试查找遮罩层元素并设置样式
  const mask = findMaskElement(parentNode);
  if (mask) {
    mask.style.pointerEvents = "none";
  }
};
// 查找遮罩层元素的辅助方法
const findMaskElement = (container) => {
  // 尝试通过常见类名查找遮罩层
  let mask = container.parentNode;
  if (mask) return mask;
  return null;
};
const handleDrawComplete = (data) => {
  console.log("handleDrawComplete", data);
};

onMounted(() => {
  //   // 添加对扇形编辑开始事件的监听
  //   window.addEventListener('cesium-entity-sx-editstart', function (event) {
  //     console.log('开始编辑扇', event.detail);
  //     let entityObj = event.detail.entityObj
  //     entityData.value = entityObj;
  //     drawsectorfrom(entityObj, sectorfrom.value, treeData.value);
  //   });
  //   window.addEventListener('cesium-entity-sx-editing', function (event) {
  //     console.log('正在编辑', event.detail);
  //     let entityObj = event.detail.entityObj
  //     entityData.value = entityObj;
  //     drawsectorfrom(entityObj, sectorfrom.value, treeData.value);
  //   });
  window.addEventListener('sh-editing', function (event) {
    console.log('正在编辑', event.detail);
    let entityObj = event.detail.entityObj
    entityData.value = entityObj;
    drawsectorringfrom(entityObj, sectorRingfrom.value, treeData.value);
  });

  //   // 添加对扇形编辑结束事件的监听
  //   window.addEventListener('cesium-entity-sx-editend', function (event) {
  //     console.log('结束编辑');
  //     isponit.value = false;
  //     showDrawSectorDialog.value = false;
  //     if (pointTools.value) {
  //       editpointTools.value.removeOne(pointTools.value);
  //     }
  //   });
  //   // 添加对扇环编辑开始事件的监听
  // window.addEventListener('sh-start', function (event) {
  //   console.log('开始编辑扇环', event.detail);
  //   let entityObj = event.detail.entityObj
  //   entityData.value = entityObj;
  //   // if (str == "开始") {
  //   //   isponit.value = false;
  //   // } else {
  //   //   isponit.value = true;
  //   // }
  //   drawsectorringfrom(entityObj, sectorRingfrom.value, treeData.value);
  // });
  // window.addEventListener('sh-end', function (event) {
  //   console.log('结束编辑扇环', event.detail);

  //   isponit.value = false;
  //   showDrawSectorRingDialog.value = false;
  //   if (pointTools.value) {
  //     editpointTools.value.removeOne(pointTools.value);
  //   }
  //   // drawsectorringfrom(entityObj, sectorRingfrom.value, treeData.value);
  //   // 检查event.detail.entityObj是否存在，避免错误
  //   if (event.detail && event.detail.entityObj) {
  //     drawsectorringfrom(event.detail.entityObj, sectorRingfrom.value, treeData.value);
  //   }
  // });
});





</script>

<style scoped>
:deep(.box-item .el-popover.el-popper) {
  min-width: 114px !important;
  width: 114px;
}

.X_Plot_leftbox {
  position: relative;
  /* height: 100%; */
  height: 50%;
}

.X_Plot_content {
  position: absolute;
  width: 100px;
  /* height: 100%; */
  height: 80%;
  top: 138px;
  left: 0;
}

.X_Plot_left {
  position: absolute;
  width: 36px;

  left: 30px;
  margin-top: 93px;
  /* background: red; */
}

.X_Plot_left_item {
  width: 36px;
  height: 36px;
  margin-top: 20px;
}

.X_Plot_left_item_active {
  width: 16px;
  height: 16px;
  cursor: pointer;
  position: absolute;
  top: -7px;
  right: -7px;
}

.shake {
  animation: shake 0.5s linear infinite;
}

@keyframes shake {
  0% {
    transform: translateX(0);
    transform: translateY(0);
  }

  25% {
    transform: translateX(-1px);
    /* transform: translateY(-1px); */
  }

  50% {
    transform: translateX(1px);
    transform: translateY(1px);
  }

  75% {
    transform: translateX(-1px);
    /* transform: translateY(-1px); */
  }

  100% {
    transform: translateX(0);
    transform: translateY(0);
  }
}
</style>
